package com.edu.hre.struts.action.admin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.entity.HrePageInfo;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.DynamicConfig;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.db.pojo.HreConfig;
import com.edu.hre.db.pojo.HreUserRoleScreen;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.struts.form.admin.ConfigurationForm;
import com.edu.hre.struts.form.admin.ConfigurationListForm;

public class ConfigurationListAction extends DispatchAction {

	private static final Logger logger = Logger.getLogger(ConfigurationListAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "adminConfigs";

	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		HreUserRoleScreen userRoleScreen = (HreUserRoleScreen) request.getSession().getAttribute(RequestUtils.Attribute.HreUserRoleScreen);
		ConfigurationListForm beanForm = (ConfigurationListForm) form;
		beanForm.setCanAdd(userRoleScreen.isCanCreate());
		beanForm.setCanDelete(userRoleScreen.isCanDelete()); 
		String sortBy = RequestUtils.getParameterStr(request, "sort", null);

		if (sortBy != null) { 
			beanForm.setAsc(!beanForm.isAsc());
			CommonUtils.sortCollection(beanForm.getListConfigs(), beanForm.isAsc(), sortBy);
			return mapping.findForward(ACTION_NAME);
		}
		int currentPage = RequestUtils.getParameterInt(request, "page", 1);
		int pageSize = CommonUtils.parseInt(DynamicConfig.getConfig(DynamicConfig.PAGE_SIZE), 20);
		List <HreConfig> listConfigs = baseService.getPojos(null, -1, null, new String[]{"dateCreated"}, new Boolean[]{true}, pageSize, pageSize * (currentPage - 1), HreConfig.class);
		List<ConfigurationForm> listConfigsForm = new ArrayList<ConfigurationForm>();
		for(HreConfig tmp : listConfigs){
			listConfigsForm.add(new ConfigurationForm(tmp.getId(), tmp.getKey1(), tmp.getValue(), tmp.getComment()));
		}
		beanForm.setListConfigs(listConfigsForm);
		int totalItems = baseService.countByColumns(null, null, null, "key1", HreConfig.class);
		List<HrePageInfo> listPages = CommonUtils.getDisplayingPages(currentPage, CommonUtils.getTotalPage(totalItems));
		beanForm.setListPages(listPages);
		beanForm.setTotalItems(totalItems);
		beanForm.setTotalPage(CommonUtils.getTotalPage(totalItems));
		
		return mapping.findForward(ACTION_NAME);
	}
}
